//
//  AppDelegate.m
//  Everest
//
//  Created by 李其昌 on 14/12/17.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "AppDelegate.h"
#import "DownloadViewController.h"
#import "PlayViewController.h"
#import "FindViewController.h"
#import "MineViewController.h"
#import "LeftViewController.h"
#import "LogInViewController.h"
#import "MMDrawerBaseNavigationViewController.h"
#import "MMDrawerController.h"
#import "MMExampleDrawerVisualStateManager.h"
#import "WeiboSDK.h"
#import "Reachability.h"
#import "NewDownloadViewController.h"
#define APPKEY @"3856338914"
#define REDIRECTURI @"http://www.sharesdk.cn"

@interface AppDelegate ()<WeiboSDKDelegate, UIAlertViewDelegate, UITabBarControllerDelegate>
@property (nonatomic,strong) MMDrawerController * drawerController;
@property (nonatomic, retain) AFNetworkReachabilityManager *manager;
@property(nonatomic,retain)UIView *nightView;

@end

@implementation AppDelegate

@synthesize wbtoken;
@synthesize wbCurrentUserID;

- (void)dealloc
{
    [_manager release];
    [_drawerController release];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    // 左抽屉
    LeftViewController * leftSideDrawerViewController = [[LeftViewController alloc] init];
    
    // 发现主页面
    FindViewController * find = [[FindViewController alloc] init];
    
    // 将发现主页面加到自定义的视图控制器中
    MMDrawerBaseNavigationViewController * navigationController = [[MMDrawerBaseNavigationViewController alloc] initWithRootViewController:find];
    // 给发现视图控制器加一个恢复标识
    [navigationController setRestorationIdentifier:@"MMExampleCenterNavigationControllerRestorationKey"];
    // 判断是否是ios7及以上
    if(OSVersionIsAtLeastiOS7()){
        // 给左视图控制器加一个恢复标识
        [leftSideDrawerViewController setRestorationIdentifier:@"MMExampleLeftNavigationControllerRestorationKey"];
        // 创建并初始化抽屉视图控制器给他一个主视图, 和左视图
        self.drawerController = [[MMDrawerController alloc]
                                 initWithCenterViewController:navigationController
                                 leftDrawerViewController:leftSideDrawerViewController
                                 rightDrawerViewController:nil];
        // 是否显示阴影, 否
        [self.drawerController setShowsShadow:NO];
    }
    // 如果是ios7以下
    else{
        // 则直接添加
        self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:navigationController leftDrawerViewController:leftSideDrawerViewController rightDrawerViewController:nil];
    }
    // 给视图控制器一个恢复标识
    [self.drawerController setRestorationIdentifier:@"MMDrawer"];
    // 设置左视图宽度
    [self.drawerController setMaximumLeftDrawerWidth:80.0];
    // 设置打开抽屉的状态为全部
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    // 设置关闭抽屉的状态效果为全部
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    
    // 设置抽屉的视觉状态的block
    [self.drawerController
     setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
         MMDrawerControllerDrawerVisualStateBlock block;
         block = [[MMExampleDrawerVisualStateManager sharedManager]
                  drawerVisualStateBlockForDrawerSide:drawerSide];
         if(block){
             block(drawerController, drawerSide, percentVisible);
         }
     }];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    if(OSVersionIsAtLeastiOS7()){
        UIColor * tintColor = [UIColor colorWithRed:29.0 / 255.0 green:173.0 / 255.0 blue:234.0 / 255.0 alpha:1.0];
        [self.window setTintColor:tintColor];
    }
    // 创建一个标签视图
    UITabBarController *tabBarVC = [[UITabBarController alloc] init];
    tabBarVC.delegate = self;
    NewDownloadViewController *download = [[NewDownloadViewController alloc] init];
    tabBarVC.tabBarController.tabBar.barStyle = UIBarStyleBlack;
    UINavigationController *downloadNav = [[UINavigationController alloc] initWithRootViewController:download];
    download.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"下载" image:[UIImage imageNamed:@"down.png"] selectedImage:[UIImage imageNamed:@"down.png"]] autorelease];
    
    MineViewController *mine = [[MineViewController alloc] init];
    mine.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我" image:[UIImage imageNamed:@"wo.png"] tag:6];
    UINavigationController *mineNav = [[UINavigationController alloc] initWithRootViewController:mine];
    // 创建一个视图控制器的数组, 来存放标签视图的内容
    tabBarVC.viewControllers = [NSMutableArray arrayWithObjects:self.drawerController, downloadNav,  mineNav,nil];
    self.drawerController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"发现" image:[UIImage imageNamed:@"find.png"] tag:1];
    tabBarVC.tabBarItem.imageInsets = UIEdgeInsetsMake(50, 50, 50, 50);
    self.window.rootViewController = tabBarVC;
    [tabBarVC release];
    
    
    // 设置tabbar为不透明
//    tabBarVC.tabBar.translucent = NO;
    // 设置tabbar填充色为白色
    tabBarVC.tabBar.barTintColor = [UIColor whiteColor];
    [find release];
    [navigationController release];
    [mine release];
    [mineNav release];
    [download release];
    [downloadNav release];
    
    [self.window setRootViewController:tabBarVC];
    
    
    return YES;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:1];
    
    // 后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:APPKEY];
    
    
    // 初始化窗口, 使其与屏幕一样大
    //    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // 设置窗口的背景颜色为白色
    self.window.backgroundColor = [UIColor whiteColor];
    // 将窗口显示出来
    [self.window makeKeyAndVisible];
    // 内存管理
    [_window release];
    
    
    self.nightView = [[UIView alloc] initWithFrame:self.window.bounds];
    self.nightView.userInteractionEnabled = NO;
    self.nightView.backgroundColor = [UIColor blackColor];
    self.nightView.alpha = 0.5;
    self.nightView.hidden = YES;
    [self.window addSubview:self.nightView];
    [_nightView release];
    
    
    NSNotificationCenter *ficationNight = [NSNotificationCenter defaultCenter];
    
    [ficationNight addObserver:self selector:@selector(nightAction:) name:@"night" object:nil];
    
    return YES;
}

- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
{
    NSString * key = [identifierComponents lastObject];
    if([key isEqualToString:@"MMDrawer"]){
        return self.window.rootViewController;
    }
    else if ([key isEqualToString:@"MMExampleCenterNavigationControllerRestorationKey"]) {
        return ((MMDrawerController *)self.window.rootViewController).centerViewController;
    }
    else if ([key isEqualToString:@"MMExampleRightNavigationControllerRestorationKey"]) {
        return ((MMDrawerController *)self.window.rootViewController).rightDrawerViewController;
    }
    else if ([key isEqualToString:@"MMExampleLeftNavigationControllerRestorationKey"]) {
        return ((MMDrawerController *)self.window.rootViewController).leftDrawerViewController;
    }
    else if ([key isEqualToString:@"MMExampleLeftSideDrawerController"]){
        UIViewController * leftVC = ((MMDrawerController *)self.window.rootViewController).leftDrawerViewController;
        if([leftVC isKindOfClass:[UINavigationController class]]){
            return [(UINavigationController*)leftVC topViewController];
        }
        else {
            return leftVC;
        }
        
    }
    else if ([key isEqualToString:@"MMExampleRightSideDrawerController"]){
        UIViewController * rightVC = ((MMDrawerController *)self.window.rootViewController).rightDrawerViewController;
        if([rightVC isKindOfClass:[UINavigationController class]]){
            return [(UINavigationController*)rightVC topViewController];
        }
        else {
            return rightVC;
        }
    }
    return nil;
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
    }
    else if ([response isKindOfClass:WBPaymentResponse.class])
    {
        NSString *title = NSLocalizedString(@"支付结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.payStatusCode: %@\nresponse.payStatusMessage: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBPaymentResponse *)response payStatusCode], [(WBPaymentResponse *)response payStatusMessage], NSLocalizedString(@"响应UserInfo数据", nil),response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil userInfo:response.userInfo];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"uid" object:nil userInfo:response.userInfo];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"collect" object:@"YES" userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"album" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"findclassify" object:nil userInfo:nil];

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self ];
}


// 夜间模式
- (void)nightAction:(NSNotification *)nigth
{
    
    if ([[nigth.userInfo objectForKey:@"key"] isEqualToString:@"yes"] ) {
        
        self.nightView.hidden = YES;
        
    }else {
        
        self.nightView.hidden = NO;
        
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"isLogin"];
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"]);
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
